package service

import (
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
)

func InitLogger() {
	writeSyncer := getLogWriter()
	encoder := getEncoder()
	var core zapcore.Core
	if Conf.System.Env == "debug" {
		//开发 输出到终端
		ConsoleEncoder := zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig())
		core = zapcore.NewTee(
			zapcore.NewCore(ConsoleEncoder, zapcore.Lock(os.Stdout), zapcore.DebugLevel),
		)
	} else {
		core = zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)
	}
	Zap = zap.New(core, zap.AddCaller())

	// 其他地方可以直接   zap.l().msg()
	zap.ReplaceGlobals(Zap)
}

//编码 格式等
func getEncoder() zapcore.Encoder {
	config := zapcore.EncoderConfig{
		TimeKey:        "ts",
		LevelKey:       "level",
		NameKey:        "logger",
		CallerKey:      "caller",
		FunctionKey:    zapcore.OmitKey,
		MessageKey:     "msg",
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.LowercaseLevelEncoder,
		EncodeTime:     zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05.000"),
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
	}
	return zapcore.NewJSONEncoder(config)
}

//日志切割
func getLogWriter() zapcore.WriteSyncer {
	lumberJackLogger := &lumberjack.Logger{
		Filename:   Conf.Zaps.Filename,
		MaxSize:    Conf.Zaps.MaxSize,  // 文件大小
		MaxBackups: Conf.Zaps.Backubs,  //备份数量
		MaxAge:     Conf.Zaps.Maxage,   //备份天数
		Compress:   Conf.Zaps.Compress, //是否压缩
	}
	return zapcore.AddSync(lumberJackLogger)
}
